{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2caa79ba-45e3-437c-9cb6-e433f443f0bf",
   "metadata": {},
   "source": [
    "# 代理\n",
    "\n",
    "大语言模型学习并记住许多的网络公开信息，大语言模型最常见的应用场景是，将它当作知识库，让它对给定的问题做出回答。\n",
    "\n",
    "另一种思路是将大语言模型当作推理引擎，让它基于已有的知识库，并利用新的信息（新的大段文本或者其他信息）来帮助回答问题或者进行推理LongChain的内置代理工具便是适用该场景。\n",
    "\n",
    "本节我们将会了解什么是代理，如何创建代理， 如何使用代理，以及如何与不同类型的工具集成，例如搜索引擎。\n",
    "\n",
    "**目录**\n",
    "* 使用LangChain内置工具\n",
    "    * 使用llm-math和wikipedia工具\n",
    "    * 使用PythonREPLTool工具\n",
    "* 定义自己的工具并在代理中使用\n",
    "    * 创建和使用自定义时间工具"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f32a1c8f-4d9e-44b9-8130-a162b6cca6e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv()) # read local .env file\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "631c764b-68fa-483a-80a5-9a322cd1117c",
   "metadata": {},
   "source": [
    "## LangChain内置工具"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8ab03352-1554-474c-afda-ec8974250e31",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 如果需要查看安装过程日志，可删除 -q \n",
    "# -U 安装到最新版本的 wikipedia. 其功能同 --upgrade \n",
    "!pip install -U -q wikipedia\n",
    "!pip install -q openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "bc80a8a7-a66e-4fbb-8d57-05004a3e77c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import load_tools, initialize_agent\n",
    "from langchain.agents import AgentType\n",
    "from langchain.python import PythonREPL\n",
    "from langchain.chat_models import ChatOpenAI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5a3655c-4d5e-4a86-8bf4-a11bd1525059",
   "metadata": {},
   "source": [
    "### 📚 使用llm-math和wikipedia工具"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e484d285-2110-4a06-a360-55313d6d9ffc",
   "metadata": {},
   "source": [
    "#### 1️⃣ 初始化大语言模型\n",
    "\n",
    "- 默认密钥`openai_api_key`为环境变量`OPENAI_API_KEY`。因此在运行以下代码之前，确保你已经设置环境变量`OPENAI_API_KEY`。如果还没有密钥，请[获取你的API Key](https://platform.openai.com/account/api-keys) 。\n",
    "- 默认模型`model_name`为`gpt-3.5-turbo`。\n",
    "- 更多关于模型默认参数请查看[这里](https://github.com/hwchase17/langchain/blob/master/langchain/chat_models/openai.py)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "71e5894f-fc50-478b-a3d3-58891cc46ffc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 参数temperature设置为0.0，从而减少生成答案的随机性。\n",
    "llm = ChatOpenAI(temperature=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7f75023-1825-4d74-bc8e-2c362f551fd1",
   "metadata": {
    "tags": []
   },
   "source": [
    "#### 2️⃣ 加载工具包\n",
    "- `llm-math` 工具结合语言模型和计算器用以进行数学计算\n",
    "- `wikipedia`工具通过API连接到wikipedia进行搜索查询。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "3541b866-8a35-4b6f-bfe6-66edb1d666cd",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = load_tools(\n",
    "    [\"llm-math\",\"wikipedia\"], \n",
    "    llm=llm #第一步初始化的模型\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5b4fcc8-8817-4a94-b154-3f328480e441",
   "metadata": {},
   "source": [
    "#### 3️⃣ 初始化代理\n",
    "\n",
    "- `agent`: 代理类型。这里使用的是`AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION`。其中`CHAT`代表代理模型为针对对话优化的模型，`REACT`代表针对REACT设计的提示模版。\n",
    "- `handle_parsing_errors`: 是否处理解析错误。当发生解析错误时，将错误信息返回给大模型，让其进行纠正。\n",
    "- `verbose`: 是否输出中间步骤结果。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "e7cdc782-2b8c-4649-ae1e-cabacee1a757",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent= initialize_agent(\n",
    "    tools, #第二步加载的工具\n",
    "    llm, #第一步初始化的模型\n",
    "    agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,  #代理类型\n",
    "    handle_parsing_errors=True, #处理解析错误\n",
    "    verbose = True #输出中间步骤\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b980137a-a1d2-4c19-80c8-ec380f9c1efe",
   "metadata": {
    "tags": []
   },
   "source": [
    "#### 4️⃣.1️⃣ 使用代理回答数学问题"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "1e2bcd3b-ae72-4fa1-b38e-d0ce650e1f31",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mThought: We need to calculate 25% of 300, which involves multiplication and division.\n",
      "\n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"Calculator\",\n",
      "  \"action_input\": \"300*0.25\"\n",
      "}\n",
      "```\n",
      "\n",
      "\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3mAnswer: 75.0\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mWe have the answer to the question.\n",
      "\n",
      "Final Answer: 75.0\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'What is the 25% of 300?', 'output': '75.0'}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent(\"What is the 25% of 300?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05bb0811-d71e-4016-868b-efbb651d8e59",
   "metadata": {},
   "source": [
    "✅ **总结**\n",
    "\n",
    "1. 模型对于接下来需要做什么，给出思考（Thought） \n",
    "    \n",
    "   <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>思考</strong>：我们需要计算300的25%，这个过程中需要用到乘法和除法。</p>\n",
    "\n",
    "2. 模型基于思考采取行动（Action）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>行动</strong>: 使用计算器（calculator），输入300*0.25</p>\n",
    "3. 模型得到观察（Observation）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"><strong>观察</strong>：答案: 75.0</p>\n",
    "\n",
    "4. 基于观察，模型对于接下来需要做什么，给出思考（Thought）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>思考</strong>: 我们的问题有了答案 </p>\n",
    "\n",
    "5. 给出最终答案（Final Answer）\n",
    "     <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>最终答案</strong>: 75.0 </p>\n",
    "5. 以字典的形式给出最终答案。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bdd13d06-0f0e-4918-ac28-339f524f8c76",
   "metadata": {},
   "source": [
    "#### 4️⃣.2️⃣ Tom M. Mitchell的书"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "f43b5cbf-1011-491b-90e8-09cf903fb866",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mThought: I should use Wikipedia to find the answer to this question.\n",
      "\n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"Wikipedia\",\n",
      "  \"action_input\": \"Tom M. Mitchell\"\n",
      "}\n",
      "```\n",
      "\n",
      "\u001b[0m\n",
      "Observation: \u001b[33;1m\u001b[1;3mPage: Tom M. Mitchell\n",
      "Summary: Tom Michael Mitchell (born August 9, 1951) is an American computer scientist and the Founders University Professor at Carnegie Mellon University (CMU). He is a founder and former Chair of the Machine Learning Department at CMU. Mitchell is known for his contributions to the advancement of machine learning, artificial intelligence, and cognitive neuroscience and is the author of the textbook Machine Learning. He is a member of the United States National Academy of Engineering since 2010. He is also a Fellow of the American Academy of Arts and Sciences, the American Association for the Advancement of Science and a Fellow and past President of the Association for the Advancement of Artificial Intelligence. In October 2018, Mitchell was appointed as the Interim Dean of the School of Computer Science at Carnegie Mellon.\n",
      "\n",
      "Page: Tom Mitchell (Australian footballer)\n",
      "Summary: Thomas Mitchell (born 31 May 1993) is a professional Australian rules footballer playing for the Collingwood Football Club in the Australian Football League (AFL). He previously played for the Sydney Swans from 2012 to 2016, and the Hawthorn Football Club between 2017 and 2022. Mitchell won the Brownlow Medal as the league's best and fairest player in 2018 and set the record for the most disposals in a VFL/AFL match, accruing 54 in a game against Collingwood during that season.\n",
      "\n",
      "\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mThe book that Tom M. Mitchell wrote is \"Machine Learning\".\n",
      "\n",
      "Final Answer: Machine Learning.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'Tom M. Mitchell is an American computer scientist and the Founders University Professor at Carnegie Mellon University (CMU)what book did he write?',\n",
       " 'output': 'Machine Learning.'}"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "question = \"Tom M. Mitchell is an American computer scientist \\\n",
    "and the Founders University Professor at Carnegie Mellon University (CMU)\\\n",
    "what book did he write?\"\n",
    "agent(question) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39e2f6fb-f229-4235-ad58-98a5f505800c",
   "metadata": {},
   "source": [
    "✅ **总结**\n",
    "\n",
    "1. 模型对于接下来需要做什么，给出思考（Thought） \n",
    "   <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>思考</strong>：我应该使用维基百科去搜索。</p>\n",
    "\n",
    "2. 模型基于思考采取行动（Action）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>行动</strong>: 使用维基百科，输入Tom M. Mitchell</p>\n",
    "3. 模型得到观察（Observation）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"><strong>观测</strong>: 页面: Tom M. Mitchell，页面: Tom Mitchell (澳大利亚足球运动员)</p>\n",
    "\n",
    "4. 基于观察，模型对于接下来需要做什么，给出思考（Thought）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>思考</strong>: Tom M. Mitchell写的书是Machine Learning </p>\n",
    "\n",
    "5. 给出最终答案（Final Answer）\n",
    "     <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>最终答案</strong>: Machine Learning </p>\n",
    "5. 以字典的形式给出最终答案。\n",
    "\n",
    "\n",
    "值得注意的是，模型每次运行推理的过程可能存在差异，但最终的结果一致。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5901cab6-a7c9-4590-b35d-d41c29e39a39",
   "metadata": {},
   "source": [
    "### 📚 使用PythonREPLTool工具"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12b8d837-524c-46b8-9189-504808cf1f93",
   "metadata": {},
   "source": [
    "#### 1️⃣ 创建pyhon代理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "6c60d933-168d-4834-b29c-b2b43ade80cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents.agent_toolkits import create_python_agent\n",
    "from langchain.tools.python.tool import PythonREPLTool\n",
    "\n",
    "agent = create_python_agent(\n",
    "    llm,  #使用前面一节已经加载的大语言模型\n",
    "    tool=PythonREPLTool(), #使用Python交互式环境工具（REPLTool）\n",
    "    verbose=True #输出中间步骤\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d32ed40c-cbcd-4efd-b044-57e611f5fab5",
   "metadata": {
    "tags": []
   },
   "source": [
    "#### 2️⃣ 使用代理对顾客名字进行排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "3d416f28-8fdb-4761-a4f9-d46c6d37fb3d",
   "metadata": {},
   "outputs": [],
   "source": [
    "customer_list = [[\"Harrison\", \"Chase\"], \n",
    "                 [\"Lang\", \"Chain\"],\n",
    "                 [\"Dolly\", \"Too\"],\n",
    "                 [\"Elle\", \"Elem\"], \n",
    "                 [\"Geoff\",\"Fusion\"], \n",
    "                 [\"Trance\",\"Former\"],\n",
    "                 [\"Jen\",\"Ayai\"]\n",
    "                ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "ba7f9a50-acf6-4fba-a1b9-503baa80266b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mI can use the sorted() function to sort the list of customers by last name and then first name. I will need to provide a key function to sorted() that returns a tuple of the last name and first name in that order.\n",
      "Action: Python REPL\n",
      "Action Input:\n",
      "```\n",
      "customers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\n",
      "sorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))\n",
      "for customer in sorted_customers:\n",
      "    print(customer)\n",
      "```\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m['Jen', 'Ayai']\n",
      "['Lang', 'Chain']\n",
      "['Harrison', 'Chase']\n",
      "['Elle', 'Elem']\n",
      "['Trance', 'Former']\n",
      "['Geoff', 'Fusion']\n",
      "['Dolly', 'Too']\n",
      "\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mThe customers are now sorted by last name and then first name. \n",
      "Final Answer: [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"[['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]\""
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.run(f\"\"\"Sort these customers by \\\n",
    "last name and then first name \\\n",
    "and print the output: {customer_list}\"\"\") "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6c6fd4b-1e9f-4f37-9a0f-3f69cc121ab0",
   "metadata": {
    "tags": []
   },
   "source": [
    "✅ **总结**\n",
    "\n",
    "1. 模型对于接下来需要做什么，给出思考（Thought） \n",
    "   <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>思考</strong>：我可以使用`sorted()`函数按姓氏和名字的顺序对客户列表进行排序。我需要为`sorted()`提供一个键函数，该函数返回一个元组，元组中按顺序包含姓氏和名字。</p>\n",
    "\n",
    "2. 模型基于思考采取行动（Action), 因为使用的工具不同，Action的输出也和之前有所不同，这里输出的为python代码\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>行动</strong>: 使用Python编程，输入以下代码</p>\n",
    "    \n",
    "    \n",
    "    ```python\n",
    "    customers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\n",
    "    sorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))\n",
    "    for customer in sorted_customers:\n",
    "        print(customer)\n",
    "    ```\n",
    "    <br>\n",
    "3. 模型得到观察（Observation）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"><strong>观测</strong>:</p>\n",
    "    \n",
    "    ```\n",
    "    ['Jen', 'Ayai']\n",
    "    ['Lang', 'Chain']\n",
    "    ['Harrison', 'Chase']\n",
    "    ['Elle', 'Elem']\n",
    "    ['Trance', 'Former']\n",
    "    ['Geoff', 'Fusion']\n",
    "    ['Dolly', 'Too']\n",
    "    ```\n",
    "    <br>\n",
    "    \n",
    "4. 基于观察，模型对于接下来需要做什么，给出思考（Thought）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>思考</strong>: 现在客户按照姓氏和名字的顺序进行了排序。</p>\n",
    "\n",
    "5. 给出最终答案（Final Answer）\n",
    "     <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>最终答案</strong>: [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']] </p>\n",
    "6. 返回最终答案。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16f530a5-8c50-4648-951f-4e65d15ca93f",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "#### 3️⃣ 使用调试模式"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "951048dc-0414-410d-a0e9-6ef32bbdda89",
   "metadata": {
    "tags": []
   },
   "source": [
    "在调试（debug）模式下再次运行，我们可以把上面的6步分别对应到下面的具体流程\n",
    "1. 模型对于接下来需要做什么，给出思考（Thought）\n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [chain/start] [1:chain:AgentExecutor] Entering Chain run with input</p>\n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [chain/start] [1:chain:AgentExecutor > 2:chain:LLMChain] Entering Chain run with input</p>\n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [llm/start] [1:chain:AgentExecutor > 2:chain:LLMChain > 3:llm:ChatOpenAI] Entering LLM run with input</p>\n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [llm/end] [1:chain:AgentExecutor > 2:chain:LLMChain > 3:llm:ChatOpenAI] [12.25s] Exiting LLM run with output</p>\n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\">[chain/end] [1:chain:AgentExecutor > 2:chain:LLMChain] [12.25s] Exiting Chain run with output</p>\n",
    "2. 模型基于思考采取行动（Action), 因为使用的工具不同，Action的输出也和之前有所不同，这里输出的为python代码\n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [tool/start] [1:chain:AgentExecutor > 4:tool:Python REPL] Entering Tool run with input</p>\n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [tool/end] [1:chain:AgentExecutor > 4:tool:Python REPL] [2.2239999999999998ms] Exiting Tool run with output</p>\n",
    "3. 模型得到观察（Observation）   \n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [chain/start] [1:chain:AgentExecutor > 5:chain:LLMChain] Entering Chain run with input</p>\n",
    "4. 基于观察，模型对于接下来需要做什么，给出思考（Thought）   \n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [llm/start] [1:chain:AgentExecutor > 5:chain:LLMChain > 6:llm:ChatOpenAI] Entering LLM run with input</p>\n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [llm/end] [1:chain:AgentExecutor > 5:chain:LLMChain > 6:llm:ChatOpenAI] [6.94s] Exiting LLM run with output</p>\n",
    "    \n",
    "5. 给出最终答案（Final Answer） \n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [chain/end] [1:chain:AgentExecutor > 5:chain:LLMChain] [6.94s] Exiting Chain run with output</p>\n",
    "6. 返回最终答案。\n",
    "    - <p style=\"font-family:verdana; font-size:12px;color:green\"> [chain/end] [1:chain:AgentExecutor] [19.20s] Exiting Chain run with output</p>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "92b8961b-b990-4540-a7f9-e4701dfaa616",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor] Entering Chain run with input:\n",
      "\u001b[0m{\n",
      "  \"input\": \"Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\"\n",
      "}\n",
      "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:chain:LLMChain] Entering Chain run with input:\n",
      "\u001b[0m{\n",
      "  \"input\": \"Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\",\n",
      "  \"agent_scratchpad\": \"\",\n",
      "  \"stop\": [\n",
      "    \"\\nObservation:\",\n",
      "    \"\\n\\tObservation:\"\n",
      "  ]\n",
      "}\n",
      "\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:chain:LLMChain > 3:llm:ChatOpenAI] Entering LLM run with input:\n",
      "\u001b[0m{\n",
      "  \"prompts\": [\n",
      "    \"Human: You are an agent designed to write and execute python code to answer questions.\\nYou have access to a python REPL, which you can use to execute python code.\\nIf you get an error, debug your code and try again.\\nOnly use the output of your code to answer the question. \\nYou might know the answer without running any code, but you should still run the code to get the answer.\\nIf it does not seem like you can write code to answer the question, just return \\\"I don't know\\\" as the answer.\\n\\n\\nPython REPL: A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.\\n\\nUse the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction: the action to take, should be one of [Python REPL]\\nAction Input: the input to the action\\nObservation: the result of the action\\n... (this Thought/Action/Action Input/Observation can repeat N times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question\\n\\nBegin!\\n\\nQuestion: Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\\nThought:\"\n",
      "  ]\n",
      "}\n",
      "\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:chain:LLMChain > 3:llm:ChatOpenAI] [12.25s] Exiting LLM run with output:\n",
      "\u001b[0m{\n",
      "  \"generations\": [\n",
      "    [\n",
      "      {\n",
      "        \"text\": \"I can use the sorted() function to sort the list of customers by last name and then first name. I will need to provide a key function to sorted() that returns a tuple of the last name and first name in that order.\\nAction: Python REPL\\nAction Input:\\n```\\ncustomers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\\nsorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))\\nprint(sorted_customers)\\n```\",\n",
      "        \"generation_info\": null,\n",
      "        \"message\": {\n",
      "          \"content\": \"I can use the sorted() function to sort the list of customers by last name and then first name. I will need to provide a key function to sorted() that returns a tuple of the last name and first name in that order.\\nAction: Python REPL\\nAction Input:\\n```\\ncustomers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\\nsorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))\\nprint(sorted_customers)\\n```\",\n",
      "          \"additional_kwargs\": {},\n",
      "          \"example\": false\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  ],\n",
      "  \"llm_output\": {\n",
      "    \"token_usage\": {\n",
      "      \"prompt_tokens\": 327,\n",
      "      \"completion_tokens\": 138,\n",
      "      \"total_tokens\": 465\n",
      "    },\n",
      "    \"model_name\": \"gpt-3.5-turbo\"\n",
      "  }\n",
      "}\n",
      "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:chain:LLMChain] [12.25s] Exiting Chain run with output:\n",
      "\u001b[0m{\n",
      "  \"text\": \"I can use the sorted() function to sort the list of customers by last name and then first name. I will need to provide a key function to sorted() that returns a tuple of the last name and first name in that order.\\nAction: Python REPL\\nAction Input:\\n```\\ncustomers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\\nsorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))\\nprint(sorted_customers)\\n```\"\n",
      "}\n",
      "\u001b[32;1m\u001b[1;3m[tool/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 4:tool:Python REPL] Entering Tool run with input:\n",
      "\u001b[0m\"```\n",
      "customers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\n",
      "sorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))\n",
      "print(sorted_customers)\n",
      "```\"\n",
      "\u001b[36;1m\u001b[1;3m[tool/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 4:tool:Python REPL] [2.2239999999999998ms] Exiting Tool run with output:\n",
      "\u001b[0m\"[['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]\"\n",
      "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:chain:LLMChain] Entering Chain run with input:\n",
      "\u001b[0m{\n",
      "  \"input\": \"Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\",\n",
      "  \"agent_scratchpad\": \"I can use the sorted() function to sort the list of customers by last name and then first name. I will need to provide a key function to sorted() that returns a tuple of the last name and first name in that order.\\nAction: Python REPL\\nAction Input:\\n```\\ncustomers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\\nsorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))\\nprint(sorted_customers)\\n```\\nObservation: [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]\\n\\nThought:\",\n",
      "  \"stop\": [\n",
      "    \"\\nObservation:\",\n",
      "    \"\\n\\tObservation:\"\n",
      "  ]\n",
      "}\n",
      "\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:chain:LLMChain > 6:llm:ChatOpenAI] Entering LLM run with input:\n",
      "\u001b[0m{\n",
      "  \"prompts\": [\n",
      "    \"Human: You are an agent designed to write and execute python code to answer questions.\\nYou have access to a python REPL, which you can use to execute python code.\\nIf you get an error, debug your code and try again.\\nOnly use the output of your code to answer the question. \\nYou might know the answer without running any code, but you should still run the code to get the answer.\\nIf it does not seem like you can write code to answer the question, just return \\\"I don't know\\\" as the answer.\\n\\n\\nPython REPL: A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.\\n\\nUse the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction: the action to take, should be one of [Python REPL]\\nAction Input: the input to the action\\nObservation: the result of the action\\n... (this Thought/Action/Action Input/Observation can repeat N times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question\\n\\nBegin!\\n\\nQuestion: Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\\nThought:I can use the sorted() function to sort the list of customers by last name and then first name. I will need to provide a key function to sorted() that returns a tuple of the last name and first name in that order.\\nAction: Python REPL\\nAction Input:\\n```\\ncustomers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\\nsorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))\\nprint(sorted_customers)\\n```\\nObservation: [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]\\n\\nThought:\"\n",
      "  ]\n",
      "}\n",
      "\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:chain:LLMChain > 6:llm:ChatOpenAI] [6.94s] Exiting LLM run with output:\n",
      "\u001b[0m{\n",
      "  \"generations\": [\n",
      "    [\n",
      "      {\n",
      "        \"text\": \"The customers are now sorted by last name and then first name.\\nFinal Answer: [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]\",\n",
      "        \"generation_info\": null,\n",
      "        \"message\": {\n",
      "          \"content\": \"The customers are now sorted by last name and then first name.\\nFinal Answer: [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]\",\n",
      "          \"additional_kwargs\": {},\n",
      "          \"example\": false\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  ],\n",
      "  \"llm_output\": {\n",
      "    \"token_usage\": {\n",
      "      \"prompt_tokens\": 521,\n",
      "      \"completion_tokens\": 67,\n",
      "      \"total_tokens\": 588\n",
      "    },\n",
      "    \"model_name\": \"gpt-3.5-turbo\"\n",
      "  }\n",
      "}\n",
      "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:chain:LLMChain] [6.94s] Exiting Chain run with output:\n",
      "\u001b[0m{\n",
      "  \"text\": \"The customers are now sorted by last name and then first name.\\nFinal Answer: [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]\"\n",
      "}\n",
      "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor] [19.20s] Exiting Chain run with output:\n",
      "\u001b[0m{\n",
      "  \"output\": \"[['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "import langchain\n",
    "langchain.debug=True\n",
    "agent.run(f\"\"\"Sort these customers by \\\n",
    "last name and then first name \\\n",
    "and print the output: {customer_list}\"\"\") \n",
    "langchain.debug=False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b2ba50d-53c4-4eab-9467-98f562a072cc",
   "metadata": {
    "tags": []
   },
   "source": [
    "## 定义自己的工具并在代理中使用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d8e88bdf-01d2-4adc-b2af-086ece6ba97d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 如果你需要查看安装过程日志，可删除 -q \n",
    "!pip install -q DateTime"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb92f6e4-21ab-494d-9c22-d0678050fd37",
   "metadata": {},
   "source": [
    "### 📚 创建和使用自定义时间工具"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "4b7e80e4-48d5-48f0-abeb-3dc33678ed9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入tool函数装饰器\n",
    "from langchain.agents import tool\n",
    "from datetime import date"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8990b3c6-fe05-45b6-9567-06baec267a99",
   "metadata": {},
   "source": [
    "#### 1️⃣ 使用tool函数装饰器构建自定义工具\n",
    "tool函数装饰器可以应用用于任何函数，将函数转化为LongChain工具，使其成为代理可调用的工具。\n",
    "\n",
    "我们需要给函数加上非常详细的文档字符串, 使得代理知道在什么情况下、如何使用该函数/工具。\n",
    "\n",
    "比如下面的函数`time`,我们加上了详细的文档字符串\n",
    "\n",
    "```python\n",
    "\"\"\"\n",
    "返回今天的日期，用于任何与获取今天日期相关的问题。\n",
    "输入应该始终是一个空字符串，该函数将始终返回今天的日期。\n",
    "任何日期的计算应该在此函数之外进行。\n",
    "\"\"\"\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e22a823f-3749-4bda-bac3-1b892da77929",
   "metadata": {},
   "outputs": [],
   "source": [
    "@tool\n",
    "def time(text: str) -> str:\n",
    "    \"\"\"Returns todays date, use this for any \\\n",
    "    questions related to knowing todays date. \\\n",
    "    The input should always be an empty string, \\\n",
    "    and this function will always return todays \\\n",
    "    date - any date mathmatics should occur \\\n",
    "    outside this function.\"\"\"\n",
    "    return str(date.today())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "440cb348-0ec6-4999-a6cd-81cb48b8c546",
   "metadata": {},
   "source": [
    "#### 2️⃣ 初始化代理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "09c9f59e-c14c-41b9-b6bd-0e97e8be72ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent= initialize_agent(\n",
    "    tools + [time], #将刚刚创建的时间工具加入到已有的工具中\n",
    "    llm, #初始化的模型\n",
    "    agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,  #代理类型\n",
    "    handle_parsing_errors=True, #处理解析错误\n",
    "    verbose = True #输出中间步骤\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1a10657-23f2-4f78-a247-73f272119eb4",
   "metadata": {},
   "source": [
    "#### 3️⃣ 使用代理询问今天的日期\n",
    "**注**: 代理有时候可能会出错（该功能正在开发中）。如果出现错误，请尝试再次运行它。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "f868e30b-ec67-4d76-9dc9-81ecd3332115",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mThought: I need to use the `time` tool to get today's date.\n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"time\",\n",
      "  \"action_input\": \"\"\n",
      "}\n",
      "```\n",
      "\u001b[0m\n",
      "Observation: \u001b[38;5;200m\u001b[1;3m2023-06-03\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3mI have successfully retrieved today's date using the `time` tool.\n",
      "Final Answer: Today's date is 2023-06-03.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'whats the date today?', 'output': \"Today's date is 2023-06-03.\"}"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent(\"whats the date today?\") "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "923a199f-08e8-4e70-afb5-70cd3e123acf",
   "metadata": {},
   "source": [
    "✅ **总结**\n",
    "\n",
    "1. 模型对于接下来需要做什么，给出思考（Thought） \n",
    "   <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>思考</strong>：我需要使用 time 工具来获取今天的日期</p>\n",
    "\n",
    "2. 模型基于思考采取行动（Action), 因为使用的工具不同，Action的输出也和之前有所不同，这里输出的为python代码\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>行动</strong>: 使用time工具，输入为空字符串</p>\n",
    "    \n",
    "   \n",
    "3. 模型得到观察（Observation）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"><strong>观测</strong>: 2023-06-03</p>\n",
    "    \n",
    "   \n",
    "    \n",
    "4. 基于观察，模型对于接下来需要做什么，给出思考（Thought）\n",
    "    <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>思考</strong>: 我已成功使用 time 工具检索到了今天的日期</p>\n",
    "\n",
    "5. 给出最终答案（Final Answer）\n",
    "     <p style=\"font-family:verdana; font-size:12px;color:green\"> <strong>最终答案</strong>: 今天的日期是2023-06-03.</p>\n",
    "6. 返回最终答案。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
